<template>
  <el-dialog
    v-model="dialog"
    title="批量入库"
    :before-close="handleClose"
    width="90%"
    v-loading="loading"
    destroy-on-close
    draggable
  >
    <div class="heads">
      <el-button type="primary" v-if="!companySelect" text @click="addCompany()">添加企业信息</el-button>
    </div>
    <div class="demo-drawer__content">
      <el-form :model="formData" :inline="true" size="large">
        <el-form-item label="类型" :label-width="formLabelWidth">
          <el-select v-model="formData.bill_type" placeholder="请选择">
            <el-option v-for="item in bill_type_options" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="企业" :label-width="formLabelWidth" class="custom-label">
          <el-autocomplete
            v-model="state"
            :disabled="companySelect"
            :fetch-suggestions="querySearchAsync"
            value-key="company_name"
            placeholder="请输入"
            @select="handleSelect"
          />
        </el-form-item>
        <el-form-item label="业务员" :label-width="formLabelWidth">
          <el-select v-model="uid" placeholder="请选择" :disabled="companySelect">
            <el-option v-for="item in listData" :key="item.id" :label="item.nickname" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-divider />
      <div>
        <div class="heads2">
          <div class="bolck">
            <el-button type="primary" @click="setAllEnterInvoicings(1)">一键开票</el-button>
            <el-button type="primary" @click="setAllEnterInvoicings(2)">取消开票</el-button>
          </div>
          <div class="bolck">
            <el-button type="primary" @click="setAllEnterChecks(1)">一键先款先票</el-button>
            <el-button type="primary" @click="setAllEnterChecks(2)">取消先款先票</el-button>
          </div>
          <div class="bolck">
            <el-date-picker
              v-model="value2"
              type="datetime"
              placeholder="请选择"
              :shortcuts="shortcuts"
              :format="customDateTimeFormat"
              :value-format="customDateTimeFormat"
              @change="handleDateChange"
            />
          </div>
        </div>
        <vxe-table
          border
          show-overflow
          :data="tableData"
          show-footer
          :column-config="{ resizable: true }"
          :edit-config="{ trigger: 'click', mode: 'cell' }"
          :footer-method="footerMethod"
        >
          <vxe-column type="seq" width="60" />
          <!-- <vxe-column field="billNo" title="票号" width="180" /> -->
          <vxe-column field="acceptorName" title="承兑人" />
          <vxe-column field="billAmount" title="票面金额" width="180" />
          <vxe-column field="expirationDate" title="到期日" width="180" />
          <vxe-column field="billNo" title="票号" width="180" />
          <vxe-column
            field="enter_price"
            title="每十万价格"
            :edit-render="{ name: 'input', attrs: { type: 'number', placeholder: '请输入' } }"
          >
            <template #edit="{ row }">
              <vxe-input v-model="row.enter_price" @input="handleInput(row)" type="number" placeholder="请输入" />
            </template>
          </vxe-column>
          <vxe-column
            field="enter_discount"
            title="贴息费"
            :edit-render="{ name: 'input', attrs: { type: 'number', placeholder: '请输入' } }"
          >
            <template #edit="{ row }">
              <vxe-input v-model="row.enter_discount" @input="handleDiscount(row)" type="number" placeholder="请输入" />
            </template>
          </vxe-column>
          <vxe-column
            field="enter_finally"
            title="实付金额"
            :edit-render="{ name: 'input', attrs: { type: 'number', placeholder: '请输入' } }"
          >
            <template #edit="{ row }">
              <vxe-input v-model="row.enter_finally" @input="handleFinally(row)" type="number" placeholder="请输入" />
            </template>
          </vxe-column>
          <vxe-column field="enter_time" title="入库时间" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input v-model="row.enter_time" type="datetime" placeholder="请选择入库时间" transfer />
            </template>
          </vxe-column>
          <vxe-column field="enter_invoicings" title="开票" :edit-render="{}">
            <template #default="{ row }">
              <span>{{ formatSex(row.enter_invoicings) }}</span>
            </template>
            <template #edit="{ row }">
              <vxe-select v-model="row.enter_invoicings" transfer>
                <vxe-option v-for="item in sexList1" :key="item.value" :value="item.value" :label="item.label" />
              </vxe-select>
            </template>
          </vxe-column>
          <vxe-column field="enter_checks" title="先款先票" :edit-render="{}">
            <template #default="{ row }">
              <span>{{ formatSex(row.enter_checks) }}</span>
            </template>
            <template #edit="{ row }">
              <vxe-select v-model="row.enter_checks" transfer>
                <vxe-option v-for="item in sexList1" :key="item.value" :value="item.value" :label="item.label" />
              </vxe-select>
            </template>
          </vxe-column>
          <vxe-column
            field="remark"
            title="备注"
            :edit-render="{ name: 'textarea', attrs: { type: 'textarea', placeholder: '请输入' } }"
          >
            <template #edit="{ row }">
              <vxe-textarea v-model="row.remark" placeholder="请输入" :autosize="{ minRows: 2, maxRows: 4 }" />
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <price ref="priceRef" />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="onClick" :loading="buttonLoading">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue"
// import { computed, reactive, ref } from "vue"
import { ElMessage } from "element-plus"
import price from "./price.vue"
import { companyListApi } from "@/api/conventional"
// import { GetListsResponseData } from "@/api/system/types/admin"
import { getAdminRoleListApi } from "@/api/system"
import { doBatchWarehouseApi } from "@/api/billv2"
import { knotsApi } from "@/api/bill"
// import { doBatchWarehouseApi } from "@/api/bill"
import { generatePrice, generateDiscount, sumValuesForName } from "@/utils/common"
import { VxeTablePropTypes } from "vxe-table"
const formLabelWidth = "80px"

const dialog = ref(false)
const loading = ref(false)
const buttonLoading = ref(false)
const priceRef = ref<any>()
const listData = ref<any>([])
// const listLog = ref<any>([])
const state = ref("")
const uid = ref<number>(0)
const company_id = ref<number>(0)
const tableData = ref<any>([])
const sexList1 = ref([
  { label: "是", value: 1 },
  { label: "否", value: 2 }
])
const formatSex = (value: number) => {
  if (value === 1) {
    return "是"
  }
  if (value === 2) {
    return "否"
  }
  return ""
}

//#region vxe-grid
import Decimal from "decimal.js"

// const sumNum = (list: any, field: string) => {
//   let count = 0
//   list.forEach((item: any) => {
//     count += Number(item[field])
//   })
//   return count
// }

const footerMethod: VxeTablePropTypes.FooterMethod<any> = ({ columns, data }) => {
  return [
    columns.map((column, columnIndex) => {
      if (columnIndex === 0) {
        return "统计"
      }
      if (["billAmount", "enter_discount", "enter_finally"].includes(column.field)) {
        return sumValuesForName(data, column.field)
      }

      return null
    })
  ]
}

const handleInput = (row: any) => {
  const { finallyAmount, discountAmount } = generatePrice(
    row.enter_price,
    row.enter_finally,
    row.enter_discount,
    row.billAmount,
    false
  )
  // row.enter_price = price
  row.enter_finally = finallyAmount
  row.enter_discount = discountAmount
}
const handleDiscount = (row: any) => {
  const { price, finallyAmount } = generateDiscount(
    row.enter_price,
    row.enter_finally,
    row.enter_discount,
    row.billAmount,
    false
  )
  row.enter_price = price
  row.enter_finally = finallyAmount
  // row.enter_discount = discountAmount
}
const handleFinally = (row: any) => {
  const billAmount = new Decimal(row.billAmount).times(10000)
  const enter_finally = new Decimal(row.enter_finally)
  const discountAmount = billAmount.minus(enter_finally).toNumber()
  const { price } = generateDiscount(row.enter_price, row.enter_finally, discountAmount, billAmount.toString(), true)
  row.enter_price = price.toFixed(2)
  // row.enter_finally = finallyAmount
  row.enter_discount = discountAmount
}

//#endregion

const addCompany = () => {
  if (priceRef.value) {
    priceRef.value.show()
  }
}
const getAdminList = async () => {
  await getAdminRoleListApi({
    role_ids: 2
  })
    .then((res) => {
      listData.value = res.data
    })
    .catch(() => {})
    .finally(() => {})
}
const querySearchAsync = (queryString: string, cb: (arg: any) => void) => {
  state.value = queryString
  companyListApi({
    company_name: state.value
  }).then((res) => {
    const lists = res.data
    if (lists.length == 0) {
      ElMessage.error("请先添加企业信息")
      cb([])
    } else {
      cb(lists)
    }
  })
}

const handleSelect = (item: any) => {
  console.log("value")
  console.log(item)
  uid.value = item.uid
  company_id.value = item.id
}

const companyLists = async () => {
  const data = await companyListApi({
    company_name: state.value
  })
  const lists = data.data
  if (lists.length == 0) {
    ElMessage.error("请先添加企业信息")
    return []
  }
  return lists
}

const bill_type_options = ref([
  { id: 1, label: "贴现" },
  { id: 2, label: "买票" }
])
const formData = reactive({
  bill_type: 1,
  bill_id: 0,
  recognizerDate: "",
  billNo: "",
  acceptorName: "",
  billAmount: 0,
  price: 0,
  money: 0,
  moneys: 0,
  expirationDate: "",
  billRangeUpper: "",
  billRangeLower: "",
  is_flaw: 1,
  bill_back_user: ""
})
//#region 弹框显示
const batchShow = async (row: any) => {
  tableData.value = Object.values(row)
  const column = Object.values(row).map((item: any) => item["bill_back_user"])
  let isbool = false
  let condition = ""
  column.map((item: any) => {
    if (condition == "") {
      condition = item
    } else {
      if (item != condition) {
        isbool = true
      }
    }
  })
  if (isbool) {
    ElMessage.warning("请勾选相同客户的票据")
    return
  }
  state.value = condition
  const companyData = await companyLists()
  if (companyData.length == 0) {
    return
  }
  dialog.value = true
  loading.value = true
  if (companyData?.length == 1) {
    company_id.value = companyData[0].id
    uid.value = companyData[0].uid
    companySelect.value = true
  }
  await getAdminList()
  buttonLoading.value = false
  loading.value = false
}
//#endregion
const onClick = async () => {
  handleSettlement(2)
  // ElMessageBox.confirm("是否结账?", "结账", {
  //   confirmButtonText: "是",
  //   cancelButtonText: "否",
  //   type: "warning"
  // })
  //   .then(async () => {
  //     handleSettlement(1)
  //   })
  //   .catch(() => {
  //     handleSettlement(2)
  //   })
}

async function handleSettlement(value: number) {
  try {
    // 调用接口，传递结账类型（1：先结账，2：后结账）
    await doBatchWarehouseApi({
      enter_company_id: company_id.value,
      enter_admin_id: uid.value,
      bill_type: formData.bill_type,
      batch_list: tableData.value
    })
    ElMessage.success("操作成功")
    if (value == 1) {
      await knotsApi({ company_id: company_id.value })
    }

    closes()
  } catch (error) {
    ElMessage.error("操作失败，请重试")
  }
}

const closes = () => {
  dialog.value = false
  cancelForm()
  emit("batchClose", true)
}
const handleClose = (done: () => void) => {
  done()
  closes()
}
const emit = defineEmits(["batchClose"])
const cancelForm = () => {
  buttonLoading.value = false
  loading.value = false
  dialog.value = false
}

// const getBillLogList = async () => {
//   const res = await getBillLogListApi({
//     bill_id: formData.bill_id
//   })
//   listLog.value = res.data.list
// }

const companySelect = ref<boolean>(false)

const setAllEnterInvoicings = (value: number) => {
  tableData.value.forEach((row: any) => {
    row.enter_invoicings = value
  })
}
const setAllEnterChecks = (value: number) => {
  tableData.value.forEach((row: any) => {
    row.enter_checks = value
  })
}

const value2 = ref("")
const shortcuts = [
  {
    text: "今天",
    value: new Date()
  },
  {
    text: "昨天",
    value: () => {
      const date = new Date()
      date.setDate(date.getDate() - 1)
      return date
    }
  },
  {
    text: "一周前",
    value: () => {
      const date = new Date()
      date.setDate(date.getDate() - 7)
      return date
    }
  }
]
const handleDateChange = (value: any) => {
  tableData.value.forEach((row: any) => {
    row.enter_time = value
  })
  console.log(value)
}

const customDateTimeFormat = ref<string>("YYYY-MM-DD HH:mm:ss")

defineExpose({ batchShow })
</script>

<style scoped lang="scss">
.heads {
  display: flex;
  justify-content: end;
  margin-bottom: 10px;
}

.heads div {
  margin-left: 10px;
}

.demo-drawer__footer {
  margin-top: 10px;
  display: flex;
  justify-content: end;
}

.logBox {
  margin-top: 20px;
}

.custom-label {
  font-weight: bold;
  color: #000;
}
.heads2 {
  display: flex;
  justify-content: end;
  margin-bottom: 10px;
}
.heads2 .bolck {
  margin-left: 10px;
}
</style>
<style scoped>
/* 在 scoped 样式中使用 /deep/ 选择器穿透样式隔离 */
:deep(.el-form-item__label) {
  color: red;
  font-weight: bold;
  font-size: 20px;
  /* 添加其他自定义样式 */
}
</style>
